﻿angular.module('Caltech').controller('standardController', function ($scope, Restangular, ngTableParams, $location, $stateParams) {
    'use strict';

    $scope.filters = {};

    $scope.search = function (index) {
        if ($scope.tableParams) {
            $scope.tableParams.reload();
        } else {
            $scope.tableParams = new ngTableParams({
                page: index || 1,
                count: 10
            }, {
                counts: [],
                getData: function ($defer, params) {
                    var standardNo =  $scope.filters.standardNo;
                    Restangular.all('standard')
                        .getList({
                            page: params.page(),
                            count: params.count(),
                            standardNo: standardNo || undefined
                        }).then(function (standards) {
                            params.total(standards.total);
                            $defer.resolve(standards);

                            if (params.page() > 1) {
                                $location.search('pageIndex', params.page());
                            }
                            $location.search('standardNo', standardNo || undefined);
                        });
                }
            });
        }
    };

    if ($stateParams.pageIndex || $stateParams.standardNo) {
        $scope.filters.standardNo = $stateParams.standardNo;
        $scope.search($stateParams.pageIndex);
    } else {
        $scope.search();
    }
});